# -*- coding: utf-8 -*-
import sys

sys.path.append('../..')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
import requests, json, time
from common.helper import Helper


class Spider(object):
    def __init__(self):
        self.mysql = MysqlClient()
        self.name = "泰爱保·百万医疗险（甲状腺版）"

    def genProductInfo(self):
        plan = {
            "planA": {
                # 年龄段
                "year": [str(i) for i in range(0, 18)],
                # 有无社保
                "socialSec": ["Y", "N"],
                # 一般医疗保险金
                "generalMedical": ["6000000"],
                # 重大医疗保险金
                "seriousMedical": ["6000000"],
                # 质子重离子保险金
                "extSerious": ["6000000"],
                # 保障期限
                "expire": ["1年"],
                # 交费类型
                "payType": ["年交"],
                # 投保对象
                "payObject": ["儿女"]
            },
            "planB": {
                # 年龄段
                "year": [str(i) for i in range(18, 61)],
                # 有无社保
                "socialSec": ["Y", "N"],
                # 一般医疗保险金
                "generalMedical": ["3000000"],
                # 重大医疗保险金
                "seriousMedical": ["6000000"],
                # 质子重离子保险金
                "extSerious": ["6000000"],
                # 保障期限
                "expire": ["1年"],
                # 交费类型
                "payType": ["年交"],
                # 投保对象
                "payObject": ["本人/父母/配偶"]
            },

        }
        for k in plan:
            for v in product(plan[k]["year"], plan[k]["socialSec"], plan[k]["generalMedical"],
                             plan[k]["seriousMedical"], plan[k]["extSerious"], plan[k]["expire"], plan[k]["payType"],
                             plan[k]["payObject"]):
                data = Helper.formatProductInfo(plan[k], v)
                self.mysql.cursor.execute(domain[self.name]["insert_sql"].format(**data))
                self.mysql._conn.commit()
                print(domain[self.name]["insert_sql"].format(**data))

    # 执行爬虫
    def requestJson(self, dt=None, mysql=None):

        distance = {
            "min":"0" if dt["payObject"] == "儿女" else "18",
            "max":"17" if dt["payObject"] == "儿女" else "60"
         }
        data = {"calculateData": {"calstartDate": "2020-04-11 00:00:00", "insuredInfo": [
            {"calinsuredRelationship": "01", "calinsuredBirth": "{0}-01-01".format( str( 2020- int(dt["year"]))), "minimum": distance["min"], "maximum": distance["max"]}],
                                  "calinsuredAge": dt["year"], "socialSecurity": "0" if dt["socialSec"] == "N" else "1", "calpayType": "Y", "planLiabilityList": [
                {"liabilityId": "1019009", "amount": "3000000", "liabilityName": "一般医疗保险金", "liabilityAmount": "300万"},
                {"liabilityId": "1019010", "amount": "6000000", "liabilityName": "重大疾病医疗保险金",
                 "liabilityAmount": "600万"},
                {"liabilityId": "1019008", "amount": "6000000", "liabilityName": "质子重离子医疗保险金",
                 "liabilityAmount": "600万"}], "liabilityContents": [
                {"liabilityId": "1019009", "amount": "3000000", "liabilityAmount": "300万", "liabilityName": "一般医疗保险金"},
                {"liabilityId": "1019010", "amount": "6000000", "liabilityAmount": "600万",
                 "liabilityName": "重大疾病医疗保险金"},
                {"liabilityId": "1019008", "amount": "6000000", "liabilityAmount": "600万",
                 "liabilityName": "质子重离子医疗保险金"},
                {"liabilityId": "", "amount": "", "liabilityAmount": "免费", "liabilityName": "重大疾病绿色通道"}],
                                  "planId": "1019A03201"},
                "exchangeData": {"memberId": "", "memberToken": "", "applicationId": "1248419083478732800",
                                 "applicationToken": "350ba61521444907d80667046dc8190e",
                                 "workqueueId": "1177408565983690752", "channelId": "3", "platformId": "pc",
                                 "referId": ""}}

        payload = json.dumps( data )
        r = requests.post( url = domain[self.name]["url"],headers=domain[self.name]["header"],data=payload)
        if  r.status_code == 200 and "保费试算成功" in r.text:
            price = Helper.decimalParse( r.json()["data"]["sumPremium"] )
            data = {
                "name":self.name,
                "id":dt["id"],
                "price":price
            }
            print( data )
            mysql.updatePrice( data )
        else:
            data = {
                "name":self.name,
                "id":dt["id"],
                "state":3
            }
            mysql.updateTask( data )
            print("\n/*产品价格更新失败:%d*/"%dt["id"])
    def main(self):
        Helper.runProcess( mysql=self.mysql,name=self.name,func=self.requestJson)
